<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="box">
        <div class="box_top">点击拖拽</div>
    </div>
</body>
<script>
    const box0 = document.querySelector('.box')
    const box = document.querySelector('.box_top');
    console.log(box);
    // 鼠标变箭头
    box.style.cursor = "move"
    // 文字禁止选中
    document.addEventListener('selectstart', function (e) {
        e.preventDefault();
    });
    // 坐标

    // 激活拖拽
    window.onload = function () {
        var chen = false;
        var chenX = chenY = 0;
        var chenPos = [{ x: box0.offsetLeft, y: box0.offsetTop }]
        box.onmousedown = function (e) {
            var e = e || window.e
            chen = true;
            chenX = e.clientX - box0.offsetLeft;
            chneY = e.clientY - box0.offsetTop;
            chenPos.push({ x: box0.offsetLeft, y: box0.offsetTop })
            this.setCapture && this.setCapture();
            return false
        }
        //拖拽开始
        document.onmousemove = function (e) {   
            {
                if (!chen) return;
                var e = e || window.e;
                var iL = e.clientX - chenX;
                var iT = e.clientY - chenY;
                var maxL = document.documentElement.clientWidth - box0.offsetWidth;
                var maxT = document.documentElement.clientHeight - box0.offsetHeight;

                iL = iL < 0 ? 0 : iL;
                iL = iL > maxL ? maxL : iL;

                iT = iT < 0 ? 0 : iT;
                iT = iT > maxT ? maxT : iT;

                box0.style.marginTop = box0.style.marginLeft = 0;
                box0.style.left = iL + "px";
                box0.style.top = iT + "px";

                chenPos.push({ x: iL, y: iT })

                return false
            };

        }
        //鼠标释放, 结束拖拽
        document.onmouseup = window.onblur = box.onlosecapture = function () {
            chen = false;
            box.releaseCapture && box.releaseCapture();
        };

    }
</script>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    body {
        background: #000;
    }

    .box {
        width: 300px;
        height: 150px;
        background: red;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        color: #fff;
        border-radius: 10px;
    }

    .box_top {
        width: 100%;
        height: 30px;
        border-bottom: 1px solid #fff;
        line-height: 30px;
        text-align: center
    }
</style>

</html>